<template>
  <div class="chuantu" style="position: relative;">
    <div v-if="!isshowcj">
      <el-upload class="avatar-uploader " :style="tubiaocss" action="#" :on-change="uploadok" :auto-upload="false" :show-file-list="false">
        <img v-if="img" :style="{width:widths,height:heights}" :src="img" class="avatar chuantu" >
        <div v-if="img&&!nocut" @click.stop="opencj" style="position: absolute; right:15px;top:15px;line-height: 24px; background:rgba(0,0,0,0.5); color:#fff;  width:36px; border-radius:3px; text-align:center;font-size: 12px;border-radius: 15px;" >剪裁</div>
        <div style="position: absolute; left:1px;bottom:0;line-height: 35px; background:rgba(0,0,0,0.5); color:#fff;  width:100%; border-radius:3px; text-align:center;" class="genghuan">点击图片更换</div>
        <i v-if="!img"  class="el-icon-circle-plus t_add_img" :style="tubiaocss"></i>
      </el-upload>
      <el-button v-if="img" size="medium" style="height: 40px; margin-left: 20px;"  @click="shanchu" type="text">删除</el-button>
    </div>
    <div v-if="isshowcj">
      <vueCropper
        :style="{width:widths,height:heights}"
        ref="cropper"
        :img="img"
        @mouseenter.native="enter"
        @mouseleave.native="leave"
      ></vueCropper>
      <el-button  size="medium" style="height: 40px; margin-left: 20px;"  @click="quxiao" type="text">取消</el-button>
      <el-button  size="medium" style="height: 40px; margin-left: 20px;"  @click="jiancai" type="text">保存</el-button>
    </div>

  </div>
</template>

<script>
  import * as qiniu from 'qiniu-js'
  import axios from "axios";
  export default {
    name: 'chuantu',
    props:['imgs','widths','heights','shows','bg','bgimg','nocut'],
    data() {
      return {
        img: "",
        show:false,
        isshowcj:false
      }
    },
    created() {

      if(this.imgs){
        console.log(this.imgs)
        this.img = this.imgs
      }

      if(!this.widths){
        this.widths = '200px'
      }
      if(!this.heights){
        this.heights = '200px'
      }
      if(!this.bg){
        this.bg = 'transparent'
      }

      if(!this.bgimg){
        this.bgimg = ''
      }
      if(this.bgimg==1){
        this.bgimg = require('@/../static/img/face1.png')
      }
      if(this.bgimg==2){
        this.bgimg = require('@/../static/img/face2.png')
      }
      if(this.bgimg==3){
        this.bgimg = require('@/../static/img/face3.png')
      }


      this.tubiaocss = {
        width:this.widths,
        maxHeight:this.heights,
        lineHeight:this.heights,
        background:this.bg,
        backgroundImage:"url("+this.bgimg+")"
      }
    },
    methods: {
      shanchu:function(){
        this.img = ''
        this.$emit('getimg', '')
      },

      dataURLtoFile(dataurl, filename) {
        let arr = dataurl.split(","),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, {
          type: mime
        });
      },
      getRandomChar:function(len = 11)  {
        var  x = "0123456789qwertyuioplkjhgfdsazxcvbnm" // 需要什么字符这里添加
        var  tmp = ""
        var timestamp = new Date().getTime();
        for(var  i=0;i<len;i++)  {
          tmp += x.charAt(Math.ceil(Math.random()*100000000)%x.length);
        }
        return  timestamp+tmp;
      },
      //单个图片上传
      uploadok: function(file) {
        let name = this.getRandomChar() + '.' + file.raw.name.split('.')[1]
        var that = this
        axios.post(`/api/qiniu/uploadtoken`,{name:name})
          .then(response => {
            if(response.data.msg.code == 0){

              const observer = {
                next(res){
                  console.log(res)
                  // ...
                },
                error(err){
                  console.log(err)
                  // ...
                },
                complete(res){
                  that.img = 'https://gperson.gantanhaokeji.top/'+ res.key
                  that.$emit('getimg',that.img)
                  // https://test91.91haoka.cn/500px1051021934.jpg
                  // ...
                }
              }

              const options = {
                maxWidth: 1000,
              }
              
              qiniu.compressImage(file.raw, options).then(data => {
                const observable = qiniu.upload(data.dist,name, response.data.data.token, {}, {})
                const subscription = observable.subscribe(observer) // 上传开始
              })

            }else{
              this.$message.error(response.data.msg.info);
            }
          });


      },
      enter() {
        this.$refs.cropper.startCrop(); //开始裁剪
      },
      leave() {
        this.$refs.cropper.stopCrop(); //停止裁剪
      },
      jiancai(){
        this.$refs.cropper.getCropBlob(data => {
          // do something

          var file = {
            raw:this.blobToFile(data,Date.now()),
            name:Date.now()
          }
          console.log(data)
          console.log(file)
          this.uploadok(file)
          this.isshowcj = false
        })
      },
      blobToFile(theBlob, fileName){
        theBlob.lastModifiedDate = new Date();  // 文件最后的修改日期
        theBlob.name = fileName;                // 文件名
        return new File([theBlob], fileName, {type: theBlob.type, lastModified: Date.now()});
      },
      //显示裁剪
      opencj(){
        this.isshowcj = true
      },
      //取消
      quxiao(){
        this.isshowcj = false
      }
    }
  }
</script>
<style scoped>
  .t_add_img{
    color: #005AFF;
    font-size: 34px;
    background-size: 100% 100% !important;
    background-repeat: no-repeat;
    /* position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -17px;
    margin-top: -17px; */
  }
</style>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">

    .avatar-uploader{
    	border: 1px dashed #d9d9d9;
    	border-radius: 6px;
    	cursor: pointer;
    	position: relative;
    	overflow: hidden;
      /deep/ .el-upload{ display: block;}
    }

    .avatar-uploader .el-upload:hover {
    	border-color: #409EFF;
    }

    .avatar-uploader-icon {
    	font-size: 28px;
    	color: #8c939d;

    	text-align: center;
    }

    .avatar {
    	// max-width: 194px;
    	// max-height: 194px;
    	display: block;
      img{width: 100%; display: block;}
    }
    .genghuan{ display: none;}
    .chuantu:hover{
      .genghuan{ display: block;}
    }
</style>
